<template>
  <base-table-layout
    title="库存管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-select
        v-model="searchForm.materialId"
        placeholder="请选择物资"
        style="width: 200px;"
        class="filter-item"
        clearable
      >
        <el-option
          v-for="item in materialOptions"
          :key="item.materialId"
          :label="item.materialName"
          :value="item.materialId"
        />
      </el-select>
      <el-select
        v-model="searchForm.deptId"
        placeholder="请选择仓库"
        style="width: 200px;"
        class="filter-item"
        clearable
      >
        <el-option
          v-for="item in departmentOptions"
          :key="item.deptId"
          :label="item.deptName"
          :value="item.deptId"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >批量删除</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="56"
        />
        <el-table-column prop="materialName" label="物资名称" width="180" />
        <el-table-column prop="deptName" label="仓库名称" />
        <el-table-column prop="quantity" label="库存数量" />
        <el-table-column prop="minStock" label="最小库存" />
        <el-table-column prop="maxStock" label="最大库存" />
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑库存对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="inventoryForm" :rules="rules" ref="inventoryForm" label-width="100px">
          <el-form-item label="物资" prop="materialId">
            <el-select
              v-model="inventoryForm.materialId"
              placeholder="请选择物资"
              style="width: 100%"
            >
              <el-option
                v-for="item in materialOptions"
                :key="item.materialId"
                :label="item.materialName"
                :value="item.materialId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库" prop="deptId">
            <el-select
              v-model="inventoryForm.deptId"
              placeholder="请选择仓库"
              style="width: 100%"
            >
              <el-option
                v-for="item in departmentOptions"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="库存数量" prop="quantity">
            <el-input v-model="inventoryForm.quantity"></el-input>
          </el-form-item>
          <el-form-item label="最小库存" prop="minStock">
            <el-input v-model="inventoryForm.minStock"></el-input>
          </el-form-item>
          <el-form-item label="最大库存" prop="maxStock">
            <el-input v-model="inventoryForm.maxStock"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'InventoryPage',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        materialId: '',
        deptId: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      inventoryForm: {
        materialId: '',
        deptId: '',
        quantity: '',
        minStock: '',
        maxStock: ''
      },
      departmentOptions: [],
      materialOptions: [],
      rules: {
        materialId: [
          { required: true, message: '请选择物资', trigger: 'change' }
        ],
        deptId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入库存数量', trigger: 'blur' }
        ],
        minStock: [
          { required: false, message: '请输入最小库存', trigger: 'blur' }
        ],
        maxStock: [
          { required: false, message: '请输入最大库存', trigger: 'blur' }
        ]
      },
      selectedRows: []
    }
  },
  methods: {
    async loadDepartmentTree() {
      try {
        const response = await request.get('/departments/page', {
          params: {
            current: 1,
            size: 1000,  // 增加数量以确保获取所有仓库
            deptType: 5  // 仓库类型
          }
        })
        if (response.records) {
          this.departmentOptions = response.records.map(item => ({
            deptId: item.deptId,
            deptName: item.deptName
          }))
        }
      } catch (error) {
        console.error('获取仓库数据失败:', error)
        this.$message.error('获取仓库数据失败')
        throw error
      }
    },

    flattenDepartmentTree(tree) {
      let result = []
      tree.forEach(node => {
        result.push({
          deptId: node.deptId,
          deptName: node.deptName
        })
        if (node.children && node.children.length) {
          result = result.concat(this.flattenDepartmentTree(node.children))
        }
      })
      return result
    },

    async loadMaterialList() {
      try {
        const response = await request.get('/material/materialAll')
        if (response) {
          this.materialOptions = response.map(item => ({
            materialId: item.materialId,
            materialName: item.materialName
          }))
        }
      } catch (error) {
        console.error('获取物资数据失败:', error)
        this.$message.error('获取物资数据失败')
        throw error
      }
    },

    getMaterialName(materialId) {
      const material = this.materialOptions.find(item => item.materialId === materialId)
      return material ? material.materialName : '未知物资'
    },

    getDepartmentName(deptId) {
      const dept = this.departmentOptions.find(item => item.deptId === deptId)
      return dept ? dept.deptName : '未知仓库'
    },

    async handleLoadData() {
      if (!this.materialOptions.length || !this.departmentOptions.length) {
        await Promise.all([
          this.loadMaterialList(),
          this.loadDepartmentTree()
        ])
      }

      this.loading = true
      try {
        const response = await request.get('/inventory/page', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            materialId: this.searchForm.materialId || undefined,
            deptId: this.searchForm.deptId || undefined
          }
        })
        
        if (response.records) {
          this.tableData = response.records.map(item => ({
            ...item,
            deptName: this.getDepartmentName(item.deptId),
            materialName: this.getMaterialName(item.materialId)
          }))
          this.total = response.total
        }
      } catch (error) {
        console.error('获取库存数据失败:', error)
        this.$message.error('获取库存数据失败')
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(async function () {
      this.currentPage = 1
      await this.handleLoadData()
    }, 300),

    async resetSearch() {
      this.searchForm.materialId = ''
      this.searchForm.deptId = ''
      this.currentPage = 1
      await this.handleLoadData()
    },

    handleAdd() {
      this.dialogTitle = '新增库存'
      this.inventoryForm = {
        materialId: '',
        deptId: '',
        quantity: '',
        minStock: '',
        maxStock: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = '编辑库存'
      this.inventoryForm = {
        ...row,
        inventoryId: row.inventoryId
      }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该库存信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await request.delete(`/inventory/${row.inventoryId}`)

        this.$message.success('删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    handleSelectionChange(val) {
      this.selectedRows = val
    },

    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的库存记录')
        return
      }

      try {
        await this.$confirm('确认删除选中的库存记录吗？', '提示', {
          type: 'warning'
        })

        const inventoryIds = this.selectedRows.map(row => row.inventoryId)
        await request.delete('/inventory/batch', {
          data: inventoryIds
        })

        this.$message.success('批量删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },

    async handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      await this.handleLoadData()
    },

    async handleCurrentChange(val) {
      this.currentPage = val
      await this.handleLoadData()
    },

    async submitForm() {
      try {
        const valid = await this.$refs.inventoryForm.validate()
        if (!valid) return

        const formData = {
          ...this.inventoryForm
        }

        if (this.inventoryForm.inventoryId) {
          formData.inventoryId = this.inventoryForm.inventoryId
          await request.put('/inventory', formData)
        } else {
          await request.post('/inventory', formData)
        }

        this.$message.success(this.inventoryForm.inventoryId ? '更新成功' : '添加成功')
        this.dialogVisible = false
        await this.handleLoadData()
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请稍后重试')
      }
    }
  },
  async created() {
    this.loading = true
    try {
      await Promise.all([
        this.loadDepartmentTree(),
        this.loadMaterialList()
      ])
      await this.handleLoadData()
    } catch (error) {
      console.error('初始化数据失败:', error)
      this.$message.error('初始化数据失败')
    } finally {
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.search-bar {
  margin-bottom: 20px;
}
</style>